<template>
  <div class="certificate-list">
    <div class="list-header">
      <div class="header-left">
        <el-button type="primary" plain @click="goToHome">
          <el-icon><back /></el-icon>
          返回主页
        </el-button>
        <h2>证书模板列表</h2>
      </div>
      <div class="header-actions">
        <el-button type="success" @click="goToIssuance">
          <el-icon><medal /></el-icon>
          颁发证书
        </el-button>
        <el-button type="primary" @click="createNewTemplate">
          <el-icon><plus /></el-icon>
          创建新模板
        </el-button>
      </div>
    </div>

    <div class="list-content">
      <el-empty v-if="templates.length === 0" description="暂无证书模板，请点击创建新模板" />
      
      <div v-else class="template-grid">
        <el-card 
          v-for="template in templates" 
          :key="template.templateId" 
          class="template-card"
          shadow="hover"
        >
          <div class="template-preview" @click="previewTemplate(template.templateId)">
            <div class="certificate-preview-container">
              <div class="certificate-preview-content">
                <div class="certificate-title">{{ template.templateName }}</div>
                <div class="certificate-body">
                  <div class="certificate-logo">
                    <el-icon><trophy /></el-icon>
                  </div>
                  <div class="certificate-text">
                    <p>兹证明</p>
                    <p v-if="template.fields && template.fields.some(f => f.type === 'name')">
                      <span class="highlight">{{ getFieldPreviewText(template, 'name') }}</span>
                    </p>
                    <p v-if="template.fields && template.fields.some(f => f.type === 'content')">
                      {{ getFieldPreviewText(template, 'content') }}
                    </p>
                    <p v-if="template.fields && template.fields.some(f => f.type === 'code')">
                      证书编号: <span class="highlight">{{ getFieldPreviewText(template, 'code') }}</span>
                    </p>
                  </div>
                </div>
                <div class="certificate-footer">
                  <div class="certificate-date">{{ formatDate(template.createTime) }}</div>
                </div>
              </div>
            </div>
            <div class="template-overlay">
              <div class="template-overlay-content">
                <el-icon><zoom-in /></el-icon>
                <span>点击预览</span>
              </div>
            </div>
          </div>
          <div class="template-info">
            <h3 class="template-name">{{ template.templateName }}</h3>
            <p class="template-date">创建时间: {{ formatDate(template.createTime) }}</p>
          </div>
          <div class="template-actions">
            <el-button type="danger" text @click="confirmDelete(template)">
              <el-icon><delete /></el-icon>
              删除
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="证书预览"
      width="70%"
      :before-close="handleClosePreview"
    >
      <div class="preview-container" v-loading="previewLoading">
        <img v-if="previewImageUrl" :src="previewImageUrl" class="preview-image" alt="证书预览" />
        <div v-else class="preview-placeholder">
          <el-icon><picture-filled /></el-icon>
          <span>加载预览中...</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, PictureFilled, Delete, ZoomIn, Trophy, Back, Medal } from '@element-plus/icons-vue'
import { getTemplatesByCreator, deleteTemplate as deleteTemplateApi, getTemplatePreview } from '../../api/dashboard'

const router = useRouter()
const templates = ref([])
const loading = ref(false)
const previewDialogVisible = ref(false)
const previewLoading = ref(false)
const previewImageUrl = ref('')

// 获取字段预览文本
const getFieldPreviewText = (template, fieldType) => {
  if (!template.fields) return '';
  const field = template.fields.find(f => f.type === fieldType);
  return field ? field.previewText || field.label : '';
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取模板预览图片URL
const getTemplatePreviewUrl = (backgroundPath) => {
  // 如果是OSS路径，需要通过代理访问
  if (backgroundPath.startsWith('http')) {
    return backgroundPath
  } else {
    // 如果是相对路径，添加基础URL
    return `http://localhost:8080${backgroundPath}`
  }
}

// 返回主页
const goToHome = () => {
  router.push('/main')
}

// 预览模板
const previewTemplate = async (templateId) => {
  previewDialogVisible.value = true
  previewLoading.value = true
  previewImageUrl.value = ''
  
  try {
    // 调用后端API获取预览图
    const response = await getTemplatePreview(templateId)
    // 创建Blob URL
    const blob = new Blob([response], { type: 'image/png' })
    previewImageUrl.value = URL.createObjectURL(blob)
  } catch (error) {
    console.error('获取证书预览失败:', error)
    ElMessage.error('获取证书预览失败')
  } finally {
    previewLoading.value = false
  }
}

// 关闭预览对话框
const handleClosePreview = () => {
  if (previewImageUrl.value) {
    URL.revokeObjectURL(previewImageUrl.value)
  }
  previewDialogVisible.value = false
  previewImageUrl.value = ''
}

// 加载模板列表
const loadTemplates = async () => {
  try {
    loading.value = true
    // 从localStorage获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.username) {
      ElMessage.error('未获取到用户信息，请重新登录')
      return
    }

    const response = await getTemplatesByCreator(userInfo.username)
    if (response.code === 200) {
      templates.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取证书模板列表失败')
    }
  } catch (error) {
    console.error('获取证书模板列表失败:', error)
    ElMessage.error('获取证书模板列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 创建新模板
const createNewTemplate = () => {
  router.push('/certificate/template')
}

// 确认删除
const confirmDelete = (template) => {
  ElMessageBox.confirm(
    `确定要删除模板"${template.templateName}"吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      deleteTemplate(template.templateId)
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 删除模板
const deleteTemplate = async (templateId) => {
  try {
    const response = await deleteTemplateApi(templateId)
    if (response.code === 200) {
      ElMessage.success('模板删除成功')
      // 重新加载模板列表
      loadTemplates()
    } else {
      ElMessage.error(response.message || '删除模板失败')
    }
  } catch (error) {
    console.error('删除模板失败:', error)
    ElMessage.error('删除模板失败，请重试')
  }
}

// 添加跳转到证书颁发页面的函数
const goToIssuance = () => {
  router.push('/certificate/issuance')
}

onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
.certificate-list {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z' fill='%23bdc3c7' fill-opacity='0.2' fill-rule='evenodd'/%3E%3C/svg%3E");
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 15px 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.list-content {
  min-height: 400px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.template-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.template-preview {
  height: 180px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  border-bottom: 1px solid #ebeef5;
  position: relative;
}

.certificate-preview-container {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.certificate-preview-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fffdf7;
  border: 2px solid #d4af37;
  border-radius: 2px;
  padding: 10px;
  box-sizing: border-box;
  background-image: url("data:image/svg+xml,%3Csvg width='40' height='40' viewBox='0 0 40 40' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23d4af37' fill-opacity='0.1' fill-rule='evenodd'%3E%3Cpath d='M0 40L40 0H20L0 20M40 40V20L20 40'/%3E%3C/g%3E%3C/svg%3E");
}

.certificate-title {
  text-align: center;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
  color: #333;
}

.certificate-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.certificate-logo {
  margin-bottom: 5px;
}

.certificate-logo .el-icon {
  font-size: 24px;
  color: #d4af37;
}

.certificate-text {
  text-align: center;
  font-size: 12px;
  color: #333;
}

.certificate-text p {
  margin: 2px 0;
}

.highlight {
  color: #d4af37;
  font-weight: bold;
}

.certificate-footer {
  text-align: center;
  font-size: 10px;
  color: #666;
}

.template-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.template-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #909399;
}

.template-placeholder .el-icon {
  font-size: 48px;
}

.template-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.template-overlay:hover {
  opacity: 1;
}

.template-overlay-content {
  text-align: center;
}

.template-overlay-content .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #fff;
}

.template-overlay-content span {
  color: #fff;
  font-size: 14px;
}

.template-info {
  padding: 12px;
}

.template-name {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.template-date {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.template-actions {
  display: flex;
  justify-content: flex-end;
  padding: 0 12px 12px;
  gap: 10px;
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background-color: #f5f7fa;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.preview-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.preview-placeholder .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}
</style> 